#include <gst/gst.h>
#include <stdio.h>

int   argc;
char *argv[1];


//Se instancian los objetos que se necesitan para obtener el pipeline con las propiedades del gstreamer
GMainLoop *loop;
GstElement *pipeline,
           *source,
           *decoder,
           *convert,
           *sink;
GstCaps *caps;

int escuchar(){

    argc = 1;
    argv[0] = "contenido";
    // Se comienzan a asignar las propiedades del gstreamer al pipeline
    gst_init (&argc, &argv);
    loop = g_main_loop_new (NULL, FALSE);
    /* Create gstreamer elements */
        pipeline = gst_pipeline_new ("audio-player");
        source   = gst_element_factory_make ("udpsrc","udpsrc");
        decoder  = gst_element_factory_make ("rtppcmudepay","rtppcmudepay");
        convert  = gst_element_factory_make ("mulawdec","mulawdec");
        sink     = gst_element_factory_make ("pulsesink","pulsesink");


    if (!pipeline || !source || !decoder || !convert || !sink) {
        g_printerr ("One element could not be created. Exiting.\n");
        return -1;
    }

    caps = gst_caps_from_string("application/x-rtp, media=(string)audio, clock-rate=(int)8000, encoding-name=(string)PCMU, payload=(int)0, ssrc=(guint)1350777638,clock-base=(guint)2942119800, seqnum-base=(guint)47141");

    g_object_set (G_OBJECT (source), "multicast-group","224.1.1.1" , NULL);
    g_object_set (G_OBJECT (source), "auto-multicast", TRUE, NULL);
    g_object_set (G_OBJECT (source), "port", 3000, NULL);
    g_object_set (G_OBJECT (source), "caps", caps , NULL);


    //Se agregan todas las propiedades en el pipeline
    gst_bin_add_many (GST_BIN (pipeline),source, decoder, convert, sink, NULL);

    //Se realiza un link entre las propiedades agregadas al pipeline
    gst_element_link_many (source, decoder, convert, sink, NULL);

    //Se pone en el estado actual del pipeline que ejecute.
    g_print ("Now playing...\n");
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iterate */
    g_print ("Running...\n");
    g_main_loop_run (loop);

    parar();
    return 0;

}

void parar(){

    /* Stop playback */
    g_print ("Stopping playback\n");
    gst_element_set_state (pipeline, GST_STATE_NULL);

    /* Delete the pipeline */
    g_print ("Deleting pipeline\n");
    gst_object_unref (GST_OBJECT (pipeline));
    g_main_loop_unref (loop);
}

